package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.ProductMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/product")
public class ProductController {
    @Resource
    IProductService productService;
    @Resource
    IProductCategoryService productCategoryService;
    @Resource
    IProductAttributeService productAttributeService;
    @Resource
    IProductBrandService productBrandService;
    @Resource
    ISupplierService supplierService;
    @Resource
    ProductMapper productMapper;

    /**
     * 添加产品
     * @param product
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Product product) {
        boolean res = productService.save(product);
        if(res) {
            return Result.success("添加产品成功！");
        }
        return Result.error("添加产品失败！");
    }

    /**
     * 查询所有产品
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Product> productList = productService.list();
        if(productList != null) {
            return Result.success("查询所有产品成功！", productList);
        }
        return Result.error("查询所有产品失败！");
    }

    /**
     * 分页查询所有的产品
     * @param name
     * @param brandName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String brandName,
                           @RequestParam(required = false) String categoryId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<Product> productPage = new Page<>(pageNum, pageSize);
        List<Product> productList = productMapper.getProductByPage(productPage, name, brandName, categoryId);
        for(Product product : productList) {
            if(product.getCategoryId() != null) {
                ProductCategory productCategory = productCategoryService.getById(product.getCategoryId());
                StringBuilder categoryName = new StringBuilder(productCategory.getName());
                while(productCategory.getParentCategoryId() != null) {
                    productCategory = productCategoryService.getById(productCategory.getParentCategoryId());
                    categoryName.insert(0, productCategory.getName() + "/");
                }
                product.setCategoryName(categoryName.toString());
            }
            if(product.getAttributeId() != null) {
                ProductAttribute productAttribute = productAttributeService.getById(product.getAttributeId());
                product.setAttributeDescription(productAttribute.getSpecification() + "、" + productAttribute.getColor() + "、" + productAttribute.getMaterial());
            }
            if(product.getBrandId() != null) {
                ProductBrand productBrand = productBrandService.getById(product.getBrandId());
                product.setBrandName(productBrand.getName());
            }
            if(product.getSupplierId() != null) {
                Supplier supplier = supplierService.getById(product.getSupplierId());
                product.setSupplierName(supplier.getName());
            }
        }
        Page<Product> newProductPage = new Page<>(pageNum, pageSize);
        newProductPage.setRecords(productList);
        newProductPage.setTotal(productPage.getTotal());
        return Result.success("成功查询所有产品！",newProductPage);
    }

    /**
     * 导出产品
     * @param name
     * @param brandName
     * @param response
     * @return
     */
    @GetMapping("exportProductList")
    public Result exportProductList(@RequestParam(defaultValue = "") String name,
                                         @RequestParam(defaultValue = "") String brandName,
                                         @RequestParam(required = false) String categoryId,
                                         HttpServletResponse response) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        List<Product> productList = productService.list(queryWrapper);
        for(Product product : productList) {
            if(product.getCategoryId() != null) {
                ProductCategory productCategory = productCategoryService.getById(product.getCategoryId());
                StringBuilder categoryName = new StringBuilder(productCategory.getName());
                while(productCategory.getParentCategoryId() != null) {
                    productCategory = productCategoryService.getById(productCategory.getParentCategoryId());
                    categoryName.insert(0, productCategory.getName() + "/");
                }
                product.setCategoryName(categoryName.toString());
            }
            if(product.getAttributeId() != null) {
                ProductAttribute productAttribute = productAttributeService.getById(product.getAttributeId());
                product.setAttributeDescription(productAttribute.getSpecification() + "、" + productAttribute.getColor() + "、" + productAttribute.getMaterial());
            }
            if(product.getBrandId() != null) {
                ProductBrand productBrand = productBrandService.getById(product.getBrandId());
                product.setBrandName(productBrand.getName());
            }
            if(product.getSupplierId() != null) {
                Supplier supplier = supplierService.getById(product.getSupplierId());
                product.setSupplierName(supplier.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("产品名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("产品分类");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("产品属性");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("产品品牌");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("产品主图");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("产品评分");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("产品状态");
        cell.setCellStyle(style);
        cell = row.createCell((short)8);
        cell.setCellValue("产品供应商");
        cell.setCellStyle(style);
        for (int i = 0; i < productList.size(); i++) {
            row = sheet.createRow(i + 1);
            Product product= productList.get(i);
            row.createCell((short) 0).setCellValue(product.getId());
            row.createCell((short) 1).setCellValue(product.getName());
            row.createCell((short) 2).setCellValue(product.getCategoryName());
            row.createCell((short) 3).setCellValue(product.getAttributeDescription());
            row.createCell((short) 4).setCellValue(product.getBrandName());
            row.createCell((short) 5).setCellValue(product.getPicture());
            row.createCell((short) 6).setCellValue(product.getScore());
            row.createCell((short) 7).setCellValue(product.getStatus());
            row.createCell((short) 8).setCellValue(product.getSupplierName());

        }
        String fileName = "exportProductList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductList");
    }
    /**
     * 删除一系列产品
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> productIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = productService.removeByIds(productIds);
        if(res) {
            return Result.success("删除产品成功");
        }
        return Result.error("删除产品失败！");
    }

    /**
     * 删除产品
     * @param product
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Product product) {
        boolean res = productService.removeById(product);
        if(res) {
            return Result.success("删除产品成功！");
        }
        return Result.error("删除产品失败！");
    }

    /**
     * 查找产品
     * @param product
     * @return
     */
    @PostMapping("/findOne")
    public Result findOne(@RequestBody Product product) {
        Product product1 = productService.getById(product.getId());
        if(product1 == null) {
            return Result.error("查找产品失败！");
        }
        return Result.success("查找产品成功！", product1);
    }

    /**
     * 修改产品
     * @param product
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Product product) {
        boolean res = productService.saveOrUpdate(product);
        if (res) {
            return Result.success("修改产品信息成功！");
        }
        return Result.error("修改产品信息失败！");
    }

}
